package dao

import (
	"errors"
	"fmt"
	"github.com/wonderivan/logger"
	"gorm.io/gorm"
	"k8s-platform/db"
	"k8s-platform/model"
)

var Credential credential

type credential struct{}

// 列表
func (*credential) List() ([]*model.Credential, error) {
	servers := []*model.Credential{}
	tx := db.DB.Preload("HostServers").Find(&servers)
	if tx.Error != nil {
		logger.Error(fmt.Sprintf("获取credential列表失败，%v\n", tx.Error))
		return nil, errors.New(fmt.Sprintf("获取scredential列表失败，%v\n", tx.Error))
	}
	return servers, nil
}

// 新增
func (*credential) Add(credential *model.Credential) error {
	//创建credential
	tx := db.DB.Create(&credential)
	if tx.Error != nil {
		logger.Error(fmt.Sprintf("添加credential失败，%v\n", tx.Error))
		return errors.New(fmt.Sprintf("添加credential失败，%v\n", tx.Error))
	}
	return nil
}

// 基于credential查询单个，用于新增的时候判断hostgroup是否重复
func (*credential) Has(name string) (*model.Credential, bool, error) {
	data := &model.Credential{}

	tx := db.DB.Where("name = ?", name).First(&data)
	if errors.As(tx.Error, &gorm.ErrRecordNotFound) {
		return nil, false, nil
	}

	if tx.Error != nil {
		logger.Error(fmt.Sprintf("查询credential失败了, %v\n", tx.Error))
		return nil, false, errors.New(fmt.Sprintf("查询credential失败了, %v\n", tx.Error))
	}
	return data, true, nil
}

// 基于id查询单个，用于查询单个详情
func (*credential) Get(id int64) (*model.Credential, bool, error) {
	data := &model.Credential{}
	tx := db.DB.Where("id = ?", id).Preload("HostServers").First(&data)
	if errors.Is(tx.Error, gorm.ErrRecordNotFound) {
		return nil, false, nil
	}
	if tx.Error != nil {
		logger.Error(fmt.Sprintf("查询Credential组失败, %v\n", tx.Error))
		return nil, false, errors.New(fmt.Sprintf("查询Credential组失败, %v\n", tx.Error))
	}
	return data, true, nil
}

// 更新
func (*credential) Update(credential *model.Credential) error {
	//基于ID，更新单条hostgroup的所有数据
	//更新一般是在前端表格中某条数据的更新按钮，能拿到这条数据的所有内容，是list接口返回的
	//所以这里用Updates更新所有字段
	tx := db.DB.Model(&model.Credential{}).Where("id = ?", &credential.ID).Updates(&credential)
	if tx.Error != nil {
		logger.Error(fmt.Sprintf("更新credential失败, %v\n", tx.Error))
		return errors.New(fmt.Sprintf("更新credential失败, %v\n", tx.Error))
	}
	return nil
}

// 删除
func (*credential) Delete(credential *model.Credential, id int64) error {

	//先删除关联
	err := db.DB.Model(&credential).Association("HostServers").Clear()
	if err != nil {
		logger.Error("关联删除Role:Permission失败, " + err.Error())
		return errors.New("关联删除Role:Permission失败, " + err.Error())
	}

	//再删除hostgroup数据
	tx := db.DB.Where("id = ?", id).Delete(&model.Credential{})
	if tx.Error != nil {
		logger.Error("删除Credential失败, " + tx.Error.Error())
		return errors.New("删除Credential失败, " + tx.Error.Error())
	}

	return nil
}
